/*
 * File: DataConnection.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package twss;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.google.appengine.api.rdbms.AppEngineDriver;

/**
 * The Class DataConnection.
 */
public class DataConnection
{

    /** The connection. */
    private static Connection connection = null;

    /**
     * Connect.
     * 
     * @return true, if successful
     */
    public static boolean connect()
    {
        if (connection == null)
        {
            try
            {
                connectToDb(new AppEngineDriver(), "jdbc:google:rdbms://dominionenterprises.com:triperest:foxtrotbravo/foxtrotbravo");
                return connection.isValid(10);
            } catch (SQLException e)
            {
                try
                {//If we can't connect to google, try mysql
                    connectToDb(new com.mysql.jdbc.Driver(), "jdbc:mysql://localhost:3306/foxtrotbravo?user=root&password=");
                    return connection.isValid(10);
                } catch (SQLException e2)
                {
                    e2.printStackTrace();
                    return false;
                }
            }
        }
        try
        {
            return connection.isValid(10);
        } catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * Connect to db.
     * 
     * @param driver
     *            the driver
     * @param connectionString
     *            the connection string
     * @throws SQLException
     *             the sQL exception
     */
    private static void connectToDb(Driver driver, String connectionString) throws SQLException
    {
        DriverManager.registerDriver(driver);
        connection = DriverManager
                .getConnection(connectionString);
    }

    /**
     * Get Connection.
     * 
     * @return the connection
     */
    public static Connection getConnection()
    {
        if (connection == null)
        	connect();
        return connection;
    }

}
